﻿using Oracle.ManagedDataAccess.Client;
using Server.Constant;
using Server.Enum;
using Server.Framework.Message;
using Server.Framework.Processor;
using Server.Framework.Service;
using Server.Framework.Socket;
using Server.Message.Request;
using Server.Message.Response;
using Server.Model;
using Server.OptExp;
using Server.Util;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;

namespace Server.Processor
{
    /// <summary>
    /// Author: Leil
    /// Description: 请求角色列表
    /// CreateTime: 2020/5/13 10:12:49
    /// </summary>
    [ProcessorAttr(MessageId.REQUEST_USER_LIST)]
    class RequestUserListProcessor : IProcessor
    {

        public void Process(ProtobufAppSession session, RequestBaseMessage message)
        {
            if (message is UserListReq msg)
            {
                StringBuilder conSb = new StringBuilder();
                if (msg.Condition != null)
                {
                    if (msg.Condition.OrgId != 0)
                    {
                        conSb.Append($"AND ORG_ID = {msg.Condition.OrgId}");
                    }
                    if (!string.IsNullOrEmpty(msg.Condition.LoginName))
                    {
                        conSb.Append($"AND LOGIN_NAME LIKE '%{msg.Condition.LoginName}%'");
                    }
                    if (msg.Condition.Status != 0)
                    {
                        conSb.Append($"AND STATUS = {msg.Condition.Status}");
                    }
                }

                int rowCount = CommonTool.GetRowCount("SYS_USER", conSb.ToString());

                int page = msg.Page;
                int limit = msg.Limit;
                int[] startEnd = CommonTool.ConvertStartEnd(page, limit);
                string querySql = $"SELECT * FROM (SELECT users.*, ROWNUM rn FROM (SELECT * FROM SYS_USER WHERE DEL_FLAG = 1 {conSb} ORDER BY SORT DESC) users WHERE ROWNUM <= {startEnd[1]}) WHERE rn > {startEnd[0]}";

                DbConnection connection = DBService.Instance().GetConnection();
                try
                {
                    UserListResp resp = new UserListResp(MessageId.USER_LIST)
                    {
                        Count = rowCount
                    };
                    connection.Open();
                    using (DbCommand command = connection.CreateCommand())
                    {
                        command.CommandText = querySql;
                        using (DbDataReader reader = command.ExecuteReader())
                        {
                            
                            while (reader.Read())
                            {
                                UserDao user = new UserDao()
                                {
                                    ID = Convert.ToInt32(reader["ID"]),
                                    OrgId = Convert.ToInt32(reader["ORG_ID"]),
                                    LoginName = reader["LOGIN_NAME"].ToString(),
                                    Password = reader["PASSWORD"].ToString(),
                                    Sort = Convert.ToInt32(reader["SORT"]),
                                    Status = Convert.ToInt32(reader["STATUS"]),
                                    Creator = reader["CREATOR"].ToString(),
                                    CreateTime = reader["CREATE_TIME"].ToString(),
                                    Updator = reader["UPDATOR"].ToString(),
                                    UpdateTime = reader["UPDATE_TIME"].ToString(),
                                };
                                resp.Users.Add(user);
                            }
                        }

                        resp.Users.ForEach(user =>
                        {
                            string queryRoleIdSql = $"SELECT ROLE_ID FROM SYS_USER_ROLE WHERE USER_ID={user.ID}";
                            command.CommandText = queryRoleIdSql;
                            using (DbDataReader r = command.ExecuteReader())
                            {
                                while(r.Read())
                                {
                                    user.RoleIds.Add(Convert.ToInt32(r["ROLE_ID"]));
                                }
                            }
                        });

                    }
                    session.Send(resp);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    OperationResp resp = new OperationResp(MessageId.OPT_RESP)
                    {
                        Code = 500,
                        OptType = (int)OptType.QUERY_LIST,
                        Content = e.Message
                    };
                    session.Send(resp);
                }
                finally
                {
                    connection.Close();
                }

            }
        }




    }
}
